
# 开100个线程、每个线程对同一个数递减1
import time
import threading
# def sub():
#     global num
#     # num -=num
#     temp = num
#     time.sleep(0.01)
#     num = temp-1
# if __name__=="__main__":
#     num=100
#     L =[]
#     for i in range(100):
#         t = threading.Thread(target=sub)
#         t.start()
#         L.append(t)
#     # t.join()
#     for t in L:
#         t.join()
#     print(num) # 遇到time.sleep() cpu会切换线程

'''针对线程安全问题创建线程同步锁'''
def sub1():
    global num
    # num -=num
    # lock.acquire()
    with lock:
        temp = num
        time.sleep(0.001)
        num = temp-1
    # lock.release()
if __name__ =="__main__":
    num=100
    lock=threading.Lock()
    for i in range(100):
        t = threading.Thread(target=sub1)
        t.start()
    t.join()
    print(num)